/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.common;

import java.io.Serializable;
import java.util.UUID;

import org.sss.mapreduce.SssException;

@SuppressWarnings("serial")
public class TaskStatus extends CommonStatus implements Serializable {
  private final UUID jobID;
  private final long createdTime;
  private boolean stopped = false;
  public TaskStatus(UUID jobID) {
    this.jobID = jobID;
    this.createdTime = System.currentTimeMillis();
  }
  public UUID getJobID() {
    return jobID;
  }
  public long getCreatedTime() {
    return createdTime;
  }
  public synchronized boolean isStopped() {
    return stopped;
  }
  public synchronized void stop() {
    stopped = true;
  }
  public boolean update(CommonStatus status) {
    if (status.exception == null) {
      try {
        accumulate(status, false);
      }
      catch (SssException e) {
        exception = e;
        return false;
      }
      synchronized (this) {
        return !isStopped();
      }
    }
    else {
      synchronized (this) {
        exception = status.exception;
      }
      return false;
    }
  }
  /**
   * Get value of counter.
   *
   * Counter value is set in remote job.
   *
   * @param counterName identifier to specify counter.
   *
   * @see org.sss.mapreduce.Context#incrCounter
   */
  public Long getCounter(Enum<?> counterName) {
    return counter.get(counterName.name());
  }
  public synchronized TaskStatus getCopy() {
    TaskStatus copy = new TaskStatus(jobID);
    try {
      copy.accumulate(this);
    }
    catch (SssException e) {
      throw new RuntimeException("assert");
    }
    return copy;
  }
}
